package com.wcy.aspect;

import com.baomidou.mybatisplus.extension.api.IErrorCode;
import com.baomidou.mybatisplus.extension.exceptions.ApiException;
import com.wcy.model.R;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * <p>Title:GlobalExceptionHandler.java</p >
 * <p>Description: </p >
 * <p>Copyright: 公共服务与应急管理战略业务本部 Copyright(c)2020</p >
 * <p>Date:2021/9/16 16:51</p >
 *
 * @author wcy (wangchaoyanga@mail.taiji.com.cn)
 * @version 1.0
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 1.内部API调用的异常处理
     */
    @ExceptionHandler(ApiException.class)
    public R handlerApiException(ApiException exception){
        IErrorCode errorCode = exception.getErrorCode();
        if(errorCode != null){
            return R.fail(errorCode);
        }
        return R.fail(exception.getMessage());
    }

    /**
     * 2. 方法参数校验失败的异常
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R handlerMethodArgumentNotValidException(MethodArgumentNotValidException exception){
        BindingResult bindingResult = exception.getBindingResult();
        if(bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError != null){
                return R.fail(fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        return R.fail(exception.getMessage());
    }

    /**
     * 3.对象内部使用Validate 没有校验成功的异常
     */
    @ExceptionHandler(BindException.class)
    public R bindException(BindException bindException){
        BindingResult bindingResult = bindException.getBindingResult();
        if(bindingResult.hasErrors()){
            FieldError fieldError = bindingResult.getFieldError();
            if(fieldError != null){
                return R.fail(fieldError.getField()+fieldError.getDefaultMessage());
            }
        }
        return R.fail(bindException.getMessage());
    }
}
